<?php

namespace App\Admin\Extensions\Excel;

use App\Models\Category;
use App\Models\Medical;
use App\Models\MemberDoctor;
use App\Support\Data;
use Dcat\Admin\Grid\Exporters\AbstractExporter;
use Illuminate\Support\Str;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Illuminate\Contracts\View\View;
use Maatwebsite\Excel\Concerns\FromView;



class MedicalExporter extends AbstractExporter implements WithMapping, WithHeadings, FromView
{
    use Exportable;
    protected $fileName = '病例导出';
    protected $titles = [];
    // 图片数据
    protected $imageData;

    public function __construct()
    {
        $this->fileName = $this->fileName . date('Y-m-d H:i:s', time()) . '_' . Str::random(6) . '.xlsx'; //拼接下载文件名称
        // $this->titles = ['id' => 'ID', 'user_id' => '真实姓名', 'agent' => '代理人', 'atm_coding' => '编码', 'status' => '状态', 'created_at' => '添加时间'];
        parent::__construct();
    }

    public function view(): View
    {
        $params = request()->input();

        $where = function ($query) use ($params) {
            // 判断患者姓名
            if (isset($params['name']) && !empty($params['name'])) {
                $query->where('name', 'like', '%' . $params['name'] . '%');
            }
            // 判断来源
            if (isset($params['source']) && !empty($params['source'])) {
                $query->where('source',  $params['source']);
            }
            // 判断筛选状态
            if (isset($params['_selector']) && !empty($params['_selector'])) {
                if (isset($params['_selector']['status']) && !empty($params['_selector']['status'])) {
                    $query->where('status',  $params['_selector']['status']);
                }
            }
            // if (isset($params['_export_']) && !empty($params['_export_'])) {
            // }
        };

        $medicalModel = Medical::with(['memberDoctor' => function ($query) {
            $query->select('id', 'user_id', 'phone', 'real_name', 'unit', 'department', 'title')->where('status', 1);
        }])->where($where)->orderBy('id', 'desc')->get();

        foreach ($medicalModel as $key => &$val) {
            // 性别
            $sex = Data::getSex();
            $val['sex'] = isset($sex[$val['sex']]) ? $sex[$val['sex']] : '';
            // HP检查日期
            $val['hp_check_date'] = date('Y-m-d', strtotime($val['hp_check_date']));
            // HP检查方法
            $hp_check_method = Data::getHpCheckMethod();
            $val['hp_check_method'] = implode('、', Data::splitData($hp_check_method, $val['hp_check_method'], 5, $val['hp_check_method_input']));

            // HP检查结果
            $val['hp_check_result'] = ($val['hp_check_result'] == 1) ? '阳性' : '阴性';

            // 疾病诊断
            $disease_diagnosis = Data::getDiseaseDiagnosis();
            $val['disease_diagnosis'] = implode('、', Data::splitData($disease_diagnosis, $val['disease_diagnosis'], 6, $val['disease_diagnosis_input']));

            // 开展内镜
            $val['gastroscopy_diagnosis'] = ($val['gastroscopy_diagnosis'] == 1) ? $val['gastroscopy_diagnosis_input'] : '未开展内镜检查';

            // 病理诊断
            $val['case_diagnosis'] = ($val['case_diagnosis'] == 1) ? $val['case_diagnosis_input'] : '未开展病理检查';

            // 既往Hp感染治疗史
            $val['hp_treatment_history'] = ($val['hp_treatment_history'] == 1) ? $val['hp_treatment_history_input'] : '否';

            // 用药记录
            $val['medical_record_checkbox'] = implode('、', Data::splitData([1 => 'PPI/Pcab', 2 => '铋剂', 3 => '抗生素1', 4 => '抗生素2'], $val['medical_record_checkbox'], '', ''));

            // 开始服药时间
            $val['start_taking_medicine'] = date('Y-m-d', strtotime($val['start_taking_medicine']));

            // 停止服药时间
            $val['stop_taking_medicine'] = date('Y-m-d', strtotime($val['stop_taking_medicine']));

            // 治疗后HP检查日期
            $val['after_hp_check_date'] = date('Y-m-d', strtotime($val['after_hp_check_date']));

            // 反应发生日期
            $val['adversereaction_date'] = date('Y-m-d', strtotime($val['adversereaction_date']));

            // 是否调整用药方案
            $val['adjust_medication'] = ($val['adjust_medication'] == 1) ? $val['adjust_medication_reason'] : '否';
            // 其他症状
            // [1 => '无', 2 => '偶尔', 3 => '有时', 4 => '经常', 5 => '总是'];
            $cate1 = Data::cate1();
            // [1 => '无', 2 => '轻微', 3 => '中度', 4 => '重度'];
            $cate2 = Data::cate2();
            // [1 => '正常', 2 => '不正常'];
            $cate3 = Data::cate3();
            // 反酸
            $val['pre_other_acid_regurgitation'] = isset($cate1[$val['pre_other_acid_regurgitation']]) ? $cate1[$val['pre_other_acid_regurgitation']] : '';
            // 烧心
            $val['pre_other_heartburn'] = isset($cate1[$val['pre_other_heartburn']]) ? $cate1[$val['pre_other_heartburn']] : '';
            // 大便
            $val['pre_other_shit'] = isset($cate3[$val['pre_other_shit']]) ? $cate3[$val['pre_other_shit']] : '';
            // 疲乏
            $val['pre_other_fatigued'] = isset($cate2[$val['pre_other_fatigued']]) ? $cate2[$val['pre_other_fatigued']] : '';
            // 睡眠差
            $val['pre_other_poor_sleep'] = isset($cate2[$val['pre_other_poor_sleep']]) ? $cate2[$val['pre_other_poor_sleep']] : '';
            // 烦躁易怒
            $val['pre_other_irritability'] = isset($cate1[$val['pre_other_irritability']]) ? $cate1[$val['pre_other_irritability']] : '';
            // 焦虑
            $val['pre_other_anxiety'] = isset($cate2[$val['pre_other_anxiety']]) ? $cate2[$val['pre_other_anxiety']] : '';
            // 抑郁
            $val['pre_other_depressed'] = isset($cate2[$val['pre_other_depressed']]) ? $cate2[$val['pre_other_depressed']] : '';

            // 用药后其他症状
            // 反酸
            $val['after_other_acid_regurgitation'] = isset($cate1[$val['after_other_acid_regurgitation']]) ? $cate1[$val['after_other_acid_regurgitation']] : '';
            // 烧心
            $val['after_other_heartburn'] = isset($cate1[$val['after_other_heartburn']]) ? $cate1[$val['after_other_heartburn']] : '';
            // 大便
            $val['after_other_shit'] = isset($cate3[$val['after_other_shit']]) ? $cate3[$val['after_other_shit']] : '';
            // 疲乏
            $val['after_other_fatigued'] = isset($cate2[$val['after_other_fatigued']]) ? $cate2[$val['after_other_fatigued']] : '';
            // 睡眠差
            $val['after_other_poor_sleep'] = isset($cate2[$val['after_other_poor_sleep']]) ? $cate2[$val['after_other_poor_sleep']] : '';
            // 烦躁易怒
            $val['after_other_irritability'] = isset($cate1[$val['after_other_irritability']]) ? $cate1[$val['after_other_irritability']] : '';
            // 焦虑
            $val['after_other_anxiety'] = isset($cate2[$val['after_other_anxiety']]) ? $cate2[$val['after_other_anxiety']] : '';
            // 抑郁
            $val['after_other_depressed'] = isset($cate2[$val['after_other_depressed']]) ? $cate2[$val['after_other_depressed']] : '';

            // HP检查方法
            $after_hp_check_method = Data::getHpCheckMethod();
            $val['after_hp_check_method'] = implode('、', Data::splitData($after_hp_check_method, $val['after_hp_check_method'], 5, $val['after_hp_check_method_input']));

            // HP检查结果
            $val['after_hp_check_result'] = ($val['after_hp_check_result'] == 1) ? '阳性' : '阴性';

            // 是否有不良反应
            $val['adversereaction'] = ($val['treatment_dose'] == 1) ? '无' : '有';
            // 不良反应表现
            $adversereaction_group = Data::getAdverseReactions();
            $val['adversereaction_group'] = implode('、', Data::splitData($adversereaction_group, $val['adversereaction_group'], 16, $val['adversereaction_group_input']));
            // 是否用药后立即发生
            $val['adversereaction_immediately'] = ($val['adversereaction_immediately'] == 1) ? '是' : '否';
            // 不良反应严重情况
            $adversereaction_degree = Data::getAdverseReactionsSeverity();
            $val['adversereaction_degree'] = isset($adversereaction_degree[$val['adversereaction_degree']]) ? $adversereaction_degree[$val['adversereaction_degree']] : '';
            // 是否与观察药物相关
            $adversereaction_related = Data::getIsRelated();
            $val['adversereaction_related'] = isset($adversereaction_related[$val['adversereaction_related']]) ? $adversereaction_related[$val['adversereaction_related']] : '';

            $status = [0 => '未审核', 1 => '已审核', 2 => '驳回'];
            $val['status'] = $status[$val['status']];

            $val['examine_time'] = ($val['examine_time'] == null) ? '' : date('Y-m-d H:i:s', strtotime($val['examine_time']));
        }
        // dd($medicalModel);
        return view('exports.export', [
            'medical' => $medicalModel
        ]);
        // return view('exports.medical', [
        //     'medical' => $medicalModel
        // ]);
    }


    public function export()
    {
        // TODO: Implement export() method.
        $this->download($this->fileName)->prepare(request())->send();
        exit;
    }

    public function collection()
    {
        // TODO: Implement collection() method.
        return collect($this->buildData());
    }

    public function headings(): array
    {
        // TODO: Implement headings() method.
        return $this->titles();
    }

    public function map($row): array
    {

        // TODO: Implement map() method.
        return [
            $row['id'],
            $this->getMemberRealName($row['user_id']),
            $this->getMemberAgent($row['user_id']),
            $row['name'],
            $row['height'],
            $row['weight'],
            $this->getMedicalStatus($row['status']),
            $row['created_at'],
        ];
    }

    public function getMemberRealName($userid)
    {
        return MemberDoctor::where('user_id', $userid)->first()->real_name ?? '';
    }

    public function getMemberAgent($userid)
    {
        return MemberDoctor::where('user_id', $userid)->first()->agent ?? '';
    }

    public function getMedicalStatus($status)
    {
        $state = ['未审核', '已审核', '驳回'];
        return $state[$status];
    }
    public function startCell()
    {
        return 'A3';
    }
}
